﻿Imports ChatEngine.Client, ChatEngine.Client.Channel
Imports System.IO
Imports System.Text.RegularExpressions
Namespace Connections
    <Serializable()> _
    Public Class IRCConnection
#Region " Variables and Events"
        Event Connected()
        Protected Event UserJoin(ByVal User As String, ByVal ChannelName As String)
        Protected Event UserQuit(ByVal User As String, ByVal Reason As String)
        Protected Event UserPart(ByVal User As String, ByVal Channel As String)
        Protected Event Kicked(ByVal E As Connections.KickedEventArgs)
        Protected Event Query(ByVal User As String, ByVal Message As String, ByVal IsFirstMessage As Boolean)
        Protected Event NewMessage(ByVal User As String, ByVal Message As String, ByVal ChannelName As String)
        Protected Event InviteUser(ByVal ChannelName As String)
        Protected Event NickListRecv(ByVal ChannelName As String, ByVal e As NickListRecvArgs)
        Protected Event ChannelModeChange(ByVal E As ChannelModeArgs)
        Protected Event UserModeChange(ByVal E As UserModeArgs)
        Protected Event NickChanged(ByVal Previous As String, ByVal Newnick As String)
        Protected Event BanListReceived(ByVal E As BanListArgs)
        Protected Event IRCNotice(ByVal E As GenericEventArgs)
        Shared Event DisconnectedFromServer()
        Event ServerWindowClosed()
        Event AddLineToConsole(ByVal Info As String)
        Event NewChannel(ByVal ChannelName As String, ByVal ChannelObj As Client.Channel.IRCChannel)
        Event TopicChanged(ByVal Topic As String, ByVal ChannelName As String)
        Public Shared IsConnectedVar As Boolean
        Friend Const CtcpQuote As Char = Chr(1)
        Dim ircChan As Client.Channel.ChannelItem
        Dim Enc As Text.Encoding = Text.Encoding.Default
        Dim WithEvents TCPClient As System.Net.Sockets.TcpClient
        Dim CMEA As ChannelModeArgs
        Dim NLEA As NickListRecvArgs
        Dim BLEA As BanListArgs
        Dim UserEA As UserModeArgs
        Dim BlistItem As BanListItem
        Dim Writer As IO.StreamWriter
        Dim Reader As IO.StreamReader
        Dim Channel As Client.Channel.IRCChannel
        Dim RecvTimeout As Integer = 600
        Dim SendTimeout As Integer = 600
        Dim Message As Match
        Dim UMCI As UserModeCmbItem
        Dim I, J As Integer
        Dim arrBanList As Generic.List(Of BanListItem)
        Dim List, CNSplited, CModes, arrSplitVar As String()
        Dim CIStringArr As String()
        Dim ChanInfo As New Generic.List(Of UserModeCmbItem)
        Dim A, User, B, C, Msg, ChannelName, CNBase, OrigVal, CMCName As String
        Const TopicChangeCode = 332
        Dim InChannel As Boolean
        Shared globalCW As IChannelWindow
        Dim Timer As Timers.Timer = New Timers.Timer(120000)
        'Dim ReadThread, WriteThread As System.Threading.Thread
        Private Shared JoinRegex As New Regex("^:.*? JOIN .*$", RegexOptions.Compiled)
        Private Shared MsgRegEx As New Regex("^:.*? PRIVMSG (.).* :.*$", RegexOptions.Compiled)
        Private Shared KickRegex As New Regex("^:.*? KICK .* .*$", RegexOptions.Compiled)
#End Region
#Region " Properties and Core Functions"
        Public Shared Property GlobalWindow() As IChannelWindow
            Get
                Return globalCW
            End Get
            Set(ByVal value As IChannelWindow)
                globalCW = value
            End Set
        End Property
        Public Shared Property IsConnected() As Boolean
            Get
                Return IsConnectedVar
            End Get
            Set(ByVal value As Boolean)
                IsConnectedVar = value
                If value = False Then RaiseEvent DisconnectedFromServer()
            End Set
        End Property
        Private Sub ServerTimeout(ByVal sender As Object, ByVal e As Timers.ElapsedEventArgs)
            Timer.Enabled = False
            IsConnectedVar = False
            RaiseEvent DisconnectedFromServer()
        End Sub
        Public Sub New()
            Timer.AutoReset = True
            AddHandler Timer.Elapsed, AddressOf ServerTimeout
            ''   ReadThread = New Threading.Thread(AddressOf ThreadWorker)
            '   WriteThread = New Threading.Thread(AddressOf ThreadWorker)
            '  ReadThread.Name = "MChat Network Read Thread"
            ' WriteThread.Name = "MChat Network Write Thread"
            AddHandler DisconnectedFromServer, AddressOf HandleDisconnect

        End Sub
        Protected Sub ThreadWorker()
            Try
                Dim Data As String = ""
                While IsConnectedVar = True AndAlso Data IsNot Nothing
                    Data = Reader.ReadLine
                    ParseData(Data)
                    RaiseEvent AddLineToConsole(Data)
                    '[Global].Services.Get(Of Interfaces.ILogging).AddItem(Data, Logging.MessageType.ConnTrace)
                End While
            Catch ex As Exception
                'MsgBox(ex.ToString)
                RaiseEvent AddLineToConsole(ex.ToString)
            End Try
        End Sub
        Private Sub HandleDisconnect()
            '  ReadThread = Nothing
            ' WriteThread = Nothing
            Timer.Enabled = False
            IsConnectedVar = False
        End Sub
        Protected Function Connect(ByVal Port As Integer, ByVal Address As String) As Boolean
            Try
                If IsConnectedVar <> True Then
                    TCPClient = New System.Net.Sockets.TcpClient
                    Dim IPA As Net.IPAddress = Net.Dns.GetHostEntry(Address).AddressList(0)
                    TCPClient.NoDelay = True
                    TCPClient.Client.SetSocketOption(Net.Sockets.SocketOptionLevel.Socket, Net.Sockets.SocketOptionName.KeepAlive, 1)
                    TCPClient.SendTimeout = SendTimeout * 1000
                    TCPClient.ReceiveTimeout = RecvTimeout * 1000
                    TCPClient.Connect(IPA, Port)
                    Reader = New StreamReader(TCPClient.GetStream)
                    Writer = New StreamWriter(TCPClient.GetStream)
                    If Enc.GetPreamble().Length > 0 Then
                        Writer.WriteLine()
                    End If
                    IsConnectedVar = True
                    '   ReadThread.Start()
                    '  WriteThread.Start()
                    ThreadWorker()
                End If
            Catch ex As Exception
                'MsgBox(ex.ToString)
                '[Global].Services.Get(Of Interfaces.ILogging).AddItem("Connect: " & ex.ToString, Logging.MessageType.General)
            End Try
        End Function
        Protected Sub WriteToStream(ByVal Value As String)
            If IsConnected = True Then
                Dim Value1 As String
                Value1 = SharedVars.HostMask & " " & Value
                RaiseEvent AddLineToConsole(Value)
                Try
                    Writer.Write(Value1 & vbNewLine)
                    If Value.Contains("JOIN") Then InChannel = True
                    If Value.Contains("QUIT") Then
                        IsConnectedVar = False
                    End If
                    If Not IsNothing(Writer) Then Writer.Flush()
                Catch ex As Exception
                    RaiseEvent DisconnectedFromServer()
                End Try
            End If
        End Sub
#End Region
#Region " Message Parsing Functions"
        Private Sub ParseMessage(ByVal Val As String)
            Message = MsgRegEx.Match(Val)
            I = Val.IndexOf("!")
            A = Val.Substring(0, I)
            User = A.Replace(":", "")
            I = Val.IndexOf("PRIVMSG")
            B = Mid(Val, 1, I)
            A = Val.Replace(B, "")
            C = Mid(A, 1, A.IndexOf(":") + 1)
            A = A.Replace(C, "")
            Msg = A
            If Message.Groups(1).Value = "#" Or Message.Groups(1).Value = "!" Or Message.Groups(1).Value = "&" Or Message.Groups(1).Value = "+" Then
                A = GetChannelName(Val)
                RaiseEvent NewMessage(User, Msg, A)
            Else
                Dim FindVar As ChannelItem = SharedVars.Channels.Find(User)
                If IsNothing(FindVar.ChanObj) Then
                    CreateNewChannel(Val, User, "Query")
                    RaiseEvent Query(User, Msg, True)
                Else
                    RaiseEvent Query(User, Msg, False)
                End If
            End If
        End Sub
        Private Sub KickedFromChannel(ByVal Val As String)
            'Protected Event Kicked(ByVal User As String, ByVal Kicker As String, ByVal Reason As String, ByVal ChannelName As String)
            Dim MiscStrArr As String()
            Dim Reason As String = ""
            Message = KickRegex.Match(Val)
            I = Val.IndexOf("!")
            A = Val.Substring(0, I)
            User = A.Replace(":", "")
            I = Val.IndexOf("KICK")
            B = Mid(Val, 1, I)
            A = Val.Replace(B, "")
            ''KICK #rstat5 StatBot :reason
            OrigVal = A
            I = A.IndexOf(":")
            B = Mid(A, 1, I)
            C = A.Replace(B, "")
            Reason = C.Replace(":", "")
            MiscStrArr = A.Split(New Char() {" "})
            Dim CNBase As String = GetChannelName(Val)
            CNSplited = CNBase.Split(New Char() {" "})
            ChannelName = CNSplited(0)
            User = GetUsername(Val)
            '[Global].Services.Get(Of Interfaces.ILogging).AddItem("KickedFromChannel: " & ChannelName, Logging.MessageType.General)
            Dim KickedEA As Connections.KickedEventArgs = New Connections.KickedEventArgs
            KickedEA.KickedUser = MiscStrArr(2)
            KickedEA.Kicker = User
            KickedEA.Reason = Reason
            KickedEA.Channel = MiscStrArr(1)
            RaiseEvent Kicked(KickedEA)
        End Sub
        Private Function GetNewNick(ByVal Val As String)
            I = Val.IndexOf("!")
            A = Val.Substring(0, I)
            User = "<" & A.Replace(":", "") & ">"
            I = Val.IndexOf("NICK")
            B = Mid(Val, 1, I)
            A = Val.Replace(B, "")
            C = Mid(A, 1, A.IndexOf(":") + 1)
            A = A.Replace(C, "")
            Msg = A
            Return Trim(Msg)
        End Function
        Private Function GetChannelName(ByVal Val As String) As String
            If Val.Contains("JOIN") Or Val.Contains("QUIT") Then
                Message = JoinRegex.Match(Val)
                I = Val.IndexOf("!")
                If I > 0 Then
                    A = Val.Substring(0, I)
                    User = "<" & A.Replace(":", "") & ">"
                    If Val.Contains("JOIN") Then
                        I = Val.IndexOf("JOIN")
                    Else
                        I = Val.IndexOf("QUIT")
                    End If
                    B = Mid(Val, 1, I)
                    A = Val.Replace(B, "")
                    C = Mid(A, 1, A.IndexOf(":") + 1)
                    A = A.Replace(C, "")
                    Msg = A
                    Return Trim(Msg)
                End If
            ElseIf Not Val.Contains("JOIN") Or Not Val.Contains("QUIT") Then
                Dim CNames As String() = Val.Split(New Char() {" "})
                If Val.Contains("TOPIC") Or Val.Contains("PRIVMSG") Then
                    Return CNames(2)
                End If
                If Val.Contains("332") Then
                    Return CNames(3)
                End If
                Return CNames(2)
            End If
            Return "Nuffin'"
        End Function
        Private Function GetTopic(ByVal Val As String, ByVal IsNumericForm As Boolean) As String
            If Val.Contains("TOPIC") Or Val.Contains("332") Then
                If IsNumericForm = True Then
                    I = Val.IndexOf("#")
                    A = Mid(Val, 1, I)
                    B = Val.Replace(A, "")
                    I = B.IndexOf(":") + 1
                    C = Mid(B, 1, I)
                    A = B.Replace(C, "")
                    C = A
                    Return C
                Else
                    I = Val.IndexOf("!")
                    A = Val.Substring(0, I)
                    User = "<" & A.Replace(":", "") & ">"
                    I = Val.IndexOf("TOPIC")
                    B = Mid(Val, 1, I)
                    A = Val.Replace(B, "")
                    C = Mid(A, 1, A.IndexOf(":") + 1)
                    A = A.Replace(C, "")
                    Msg = A
                    Return A
                End If
            Else
                Return Nothing
            End If
        End Function
        Private Function GetUsername(ByVal Val As String)
            I = Val.IndexOf("!")
            If I >= 0 Then
                A = Mid(Val, 1, I)
                A = A.Replace(":", "")
            End If
            Return A
        End Function
        Private Function InviteUserToChannel(ByVal Val As String)
            I = Val.IndexOf("#")
            B = Mid(Val, 1, I)
            A = Val.Replace(B, "")
            Return A
        End Function
        Protected Function CreateNewChannel(ByVal Val As String, ByVal ChannelName As String, Optional ByVal Type As String = "") As IRCChannel
            ircChan = New ChannelItem
            If Type = "" Then
                Channel = New IRCChannel(GetChannelName(Val))
            Else
                Channel = New IRCChannel(GetUsername(Val))
            End If
            ircChan.ChanObj = Channel
            ircChan.Name = ChannelName
            SharedVars.Channels.Add(ircChan)
            '[Global].Services.Get(Of Interfaces.ILogging).AddItem("CreateNewChannel: Creating a new channel:  " & ChannelName & " Channel List Length " & SharedVars.Channels.Count, Logging.MessageType.FeedSync_Queue)
            Return Channel
        End Function
        Private Sub ParseModeVar(ByVal Val As String)
            Dim MyUserName As String
            MyUserName = SharedVars.Nick
            UserEA = New UserModeArgs
            UserEA.Setter = GetUsername(Val)
            Dim CNames As String() = Val.Split(New Char() {" "})
            UserEA.Channel = CNames(2)
            UserEA.User = GetUserFromModeVal(Val)
            If Val.Contains(MyUserName) Then Val = Val.Replace(MyUserName, "")
            CModes = Val.Split(New Char() {" "})
            CModes(4) = ""
            Dim Start As Integer = 3
            I = Start
            While I < CModes.Length
                Dim pIndex As Integer = I + 1
                For X As Integer = 0 To CModes(I).Length
                    While X < CModes(I).Length AndAlso CModes(I)(X) = "+"c
                        UserEA.ModeAction = Connections.Action.Add
                        X = X + 1
                    End While
                    While X < CModes(I).Length AndAlso CModes(I)(X) = "-"c
                        UserEA.ModeAction = Connections.Action.Remove
                        X = X + 1
                    End While
                    If X = 0 Then
                        ' Throw New Exception
                    ElseIf X < CModes(I).Length Then
                        '[Global].Services.Get(Of Interfaces.ILogging).AddItem("ParseMessage: " & CModes(I)(X), Logging.MessageType.NetworkLayer)
                        Select Case CModes(3)(X)
                            Case "q"
                                UserEA.Mode = ModeEnum.Owner
                                RaiseEvent UserModeChange(UserEA)
                            Case "a"
                                If CModes(3)(1) <> "q" Then
                                    UserEA.Mode = ModeEnum.Admin
                                    RaiseEvent UserModeChange(UserEA)
                                End If
                            Case "o"
                                If CModes(3)(1) <> "q" And CModes(3)(1) <> "a" Then
                                    UserEA.Mode = ModeEnum.Op
                                    RaiseEvent UserModeChange(UserEA)
                                End If
                            Case "h"
                                If CModes(3)(1) <> "q" And CModes(3)(1) <> "a" And CModes(3)(1) <> "o" Then
                                    UserEA.Mode = ModeEnum.HalfOP
                                    RaiseEvent UserModeChange(UserEA)
                                End If
                            Case "v"
                                'If CModes(3)(0) <> "q" And CModes(3)(0) <> "a" And CModes(3)(0) <> "o" And CModes(3)(0) <> "v" Then
                                UserEA.Mode = ModeEnum.User
                                RaiseEvent UserModeChange(UserEA)
                                ' End If
                        End Select
                    End If
                Next
                I = pIndex
                If I > 3 Then Exit While
            End While
        End Sub
        Private Function GetUserFromModeVal(ByVal Val As String) As String
            Dim CName As String() = Val.Split(New Char() {" "})
            Return CName(4)
        End Function
        Protected Sub ParseData(ByVal Val As String)
            Try
                Dim ChanTopic, ChanName, MyUserName As String
                MyUserName = SharedVars.Nick
                If IsNothing(Val) Then Exit Sub
                If Val.Contains("Found your hostname") Then
                    RaiseEvent Connected()
                End If
                If Val.Contains("JOIN") Then
                    Timer.Enabled = False
                    Dim UNvar = GetUsername(Val)
                    Dim SVNick = SharedVars.Nick
                    If Not UNvar = SVNick Then
                        '[Global].Services.Get(Of Interfaces.ILogging).AddItem("ParseData: Someone joined a channel", Logging.MessageType.FeedSync_Queue)
                        RaiseEvent UserJoin(GetUsername(Val), GetChannelName(Val))
                    Else
                        Timer.Enabled = False
                        '[Global].Services.Get(Of Interfaces.ILogging).AddItem("ParseData: Joining a channel", Logging.MessageType.FeedSync_Queue)
                        InChannel = True
                        Dim Cn As String = GetChannelName(Val)
                        Dim ChanObjVar As IRCChannel = CreateNewChannel(Val, Cn)
                        RaiseEvent NewChannel(Cn, ChanObjVar)
                    End If
                End If
                If Val.Contains("PRIVMSG") And Val.Contains("VERSION") Then
                    Timer.Enabled = False
                    '[Global].Services.Get(Of Interfaces.ILogging).AddItem("ParseData: Someone's trying to get my version", Logging.MessageType.General)
                    A = GetUsername(Val)
                    WriteToStream("NOTICE " & A & " :" & CtcpQuote & "VERSION" & " " & "MChat Build " & SharedVars.BuildString & CtcpQuote)
                End If
                If Val.Contains("PING") Then
                    Timer.Enabled = False
                    A = Val.Replace("PING :", "PONG ")
                    WriteToStream(A & vbNewLine)
                End If
                If Val.Contains("INVITE") Then
                    Timer.Enabled = False
                    '[Global].Services.Get(Of Interfaces.ILogging).AddItem("ParseData: We got invited to a channel", Logging.MessageType.General)
                    RaiseEvent InviteUser(InviteUserToChannel(Val))
                End If
                If Not InChannel = False Then
                    If Val.Contains("NOTICE") Then
                        Dim User As String = GetUsername(Val)
                        Dim MsgFinal As String
                        Message = MsgRegEx.Match(Val)
                        I = Val.IndexOf("!")
                        If I > 0 Then
                            A = Val.Substring(0, I)
                            User = A.Replace(":", "")
                            I = Val.IndexOf("NOTICE")
                            B = Mid(Val, 1, I)
                            A = Val.Replace(B, "")
                            C = Mid(A, 1, A.IndexOf(":") + 1)
                            A = A.Replace(C, "")
                            MsgFinal = A
                            RaiseEvent IRCNotice(New GenericEventArgs(MsgFinal, User))
                        End If
                    End If
                    If Val.Contains("NICK") Then
                        Timer.Enabled = False
                        ' If Not Val.Contains(SharedVars.Nick) Then
                        Dim PrevNick As String = GetUsername(Val)
                        Dim NewNick As String = GetNewNick(Val)
                        RaiseEvent NickChanged(PrevNick, NewNick)
                        'End If
                    End If
                    If Val.Contains("PART") Then
                        Timer.Enabled = False
                        A = GetUsername(Val)
                        I = Val.IndexOf("#")
                        B = Mid(Val, 1, I)
                        C = Val.Replace(B, "")
                        RaiseEvent UserPart(A, C)
                    End If
                    If Val.Contains("QUIT") Then
                        Timer.Enabled = False
                        RaiseEvent UserQuit(GetUsername(Val), GetChannelName(Val))
                    End If
                    If Val.Contains("352") And Not Val.Contains("PRIVMSG") Then
                        Timer.Enabled = False
                        CNSplited = Val.Split(New Char() {" "})
                        UMCI = New UserModeCmbItem
                        CMCName = CNSplited(3)
                        UMCI.Channel = CMCName
                        UMCI.User = CNSplited(7)
                        If CNSplited(7) = SharedVars.Nick Then SharedVars.HostMask = ":" & SharedVars.Nick & "!" & CNSplited(10) & "@" & CNSplited(5)
                        A = CNSplited(8).Replace("H*", "")
                        Select Case A
                            Case "~"
                                UMCI.Mode = ModeEnum.Owner
                            Case "&"
                                UMCI.Mode = ModeEnum.Admin
                            Case "@"
                                UMCI.Mode = ModeEnum.Op
                            Case "%"
                                UMCI.Mode = ModeEnum.HalfOP
                            Case "+"
                                UMCI.Mode = ModeEnum.User
                            Case Else
                                UMCI.Mode = ModeEnum.None
                        End Select
                        ChanInfo.Add(UMCI)
                    End If
                    If Val.Contains("315") And Not Val.Contains("PRIVMSG") Then
                        Timer.Enabled = False
                        CMEA = New ChannelModeArgs(ChanInfo, CMCName)
                        RaiseEvent ChannelModeChange(CMEA)
                    End If
                    If Val.Contains("353") And Not Val.Contains("PRIVMSG") Then
                        Timer.Enabled = False
                        Dim NewNicks As String()
                        '[Global].Services.Get(Of Interfaces.ILogging).AddItem("ParseData: Nick list received", Logging.MessageType.General)
                        I = Val.LastIndexOf(":")
                        A = Mid(Val, 1, I)
                        B = Val.Replace(A, "")
                        C = B.Replace(":", "")
                        If List IsNot Nothing Then
                            NewNicks = B.Split(New Char() {" "})
                            Dim X = List.Length - 1
                            Array.Resize(List, 10 + NewNicks.Length + List.Length)
                            ' [Global].Services.Get(Of Interfaces.ILogging).AddItem("ParseData: " & "", Logging.MessageType.NetworkLayer)
                            NewNicks.CopyTo(List, X)
                        Else
                            List = B.Split(New Char() {" "})
                        End If
                        Try
                            If Val.Contains("=") Then
                                I = Val.LastIndexOf("=")
                            ElseIf Val.Contains("@") Then
                                I = Val.IndexOf("@")
                            ElseIf Val.Contains("*") Then
                                I = Val.LastIndexOf("*")
                            End If
                            A = Mid(Val, 1, I)
                            B = Val.Replace(A, "")
                            If Val.Contains("=") Then
                                C = B.Replace("=", "")
                            ElseIf Val.Contains("@") Then
                                C = B.Replace("@", "")
                            ElseIf Val.Contains("*") Then
                                C = B.Replace("*", "")
                            End If
                            I = C.LastIndexOf(":")
                            A = Mid(C, 1, I)
                        Catch ex As Exception
                            RaiseEvent AddLineToConsole(ex.ToString)
                        End Try
                    End If
                    If Val.Contains("366") And Not Val.Contains("PRIVMSG") Then
                        Timer.Enabled = False
                        NLEA = New NickListRecvArgs(List, Trim(A))
                        List = Nothing
                        RaiseEvent NickListRecv(Trim(A), NLEA)
                        NLEA = Nothing
                    End If
                    If Val.Contains("367") And Not Val.Contains("PRIVMSG") Then
                        Timer.Enabled = False
                        If arrBanList IsNot Nothing Then
                            arrSplitVar = Val.Split(New Char() {" "})
                            BlistItem = New BanListItem
                            BlistItem.BannedBy = arrSplitVar(5)
                            BlistItem.Channel = arrSplitVar(3)
                            BlistItem.HostMask = arrSplitVar(4)
                            arrBanList.Add(BlistItem)
                        Else
                            arrBanList = New Generic.List(Of BanListItem)
                            arrSplitVar = Val.Split(New Char() {" "})
                            BlistItem = New BanListItem
                            BlistItem.BannedBy = arrSplitVar(5)
                            BlistItem.Channel = arrSplitVar(3)
                            BlistItem.HostMask = arrSplitVar(4)
                            arrBanList.Add(BlistItem)
                        End If
                    End If
                    If Val.Contains("368") And Not Val.Contains("PRIVMSG") Then
                        Timer.Enabled = False
                        BLEA = New BanListArgs(arrBanList, Trim(A))
                        RaiseEvent BanListReceived(BLEA)
                        arrBanList = Nothing : arrSplitVar = Nothing
                    End If
                    If Val.Contains("332") And Not Val.Contains("PRIVMSG") Then
                        Timer.Enabled = False
                        ChanTopic = GetTopic(Val, True)
                        ChanName = GetChannelName(Val)
                        '[Global].Services.Get(Of Interfaces.ILogging).AddItem("ParseData: Someone changed the topic on " & ChanName, Logging.MessageType.General)
                        RaiseEvent TopicChanged(ChanTopic, ChanName)
                    ElseIf Val.Contains("TOPIC") Then
                        Timer.Enabled = False
                        ChanTopic = GetTopic(Val, False)
                        ChanName = GetChannelName(Val)
                        '[Global].Services.Get(Of Interfaces.ILogging).AddItem("ParseData: Someone changed the topic on " & ChanName, Logging.MessageType.General)
                        RaiseEvent TopicChanged(ChanTopic, ChanName)
                    End If
                    If Val.Contains("KICK") And Val <> Nothing Then
                        If Not Val.Contains("972") Then
                            Timer.Enabled = False
                            ' [Global].Services.Get(Of Interfaces.ILogging).AddItem("ParseData: You've been counter detected. Continue with your mission.", Logging.MessageType.General)
                            KickedFromChannel(Val)
                        Else
                            Timer.Enabled = False

                            Dim KickedEA As Connections.KickedEventArgs = New Connections.KickedEventArgs
                            KickedEA.Channel = "Any"
                            KickedEA.KickedUser = MyUserName
                            KickedEA.Kicker = "ChanServer"
                            KickedEA.Reason = "You can't kick a channel admin"
                            RaiseEvent Kicked(KickedEA)
                        End If
                    End If
                    If Val.Contains("433") And Not Val.Contains("PRIVMSG") Then
                        'Dim currentserv As ChatEngine.ServerManagement.Server = SharedVars.Servers.Find(
                        'WriteToStream("NICKSERV GHOST  " & SharedVars.Nick & "")
                    End If
                    If Val.Contains("MODE") Then
                        Timer.Enabled = False
                        ParseModeVar(Val)
                    End If
                    If Val.Contains("PRIVMSG") Then 'And Not Val.Contains(CtcpQuote) Then
                        Timer.Enabled = False
                        '[Global].Services.Get(Of Interfaces.ILogging).AddItem("ParseData: New message trafic received.", Logging.MessageType.FeedSync_Queue)
                        ParseMessage(Val)
                    End If
                End If
                'Timer.Enabled = True
            Catch ex As Exception
                MsgBox(ex.ToString)
            End Try
        End Sub
#End Region
    End Class
End Namespace